<template>
  <div class="media-manager">
    <div class="page-header">
      <h1 class="page-title">媒体管理</h1>
      <div class="page-actions">
        <button class="upload-btn primary-btn" @click="showUploadModal = true">
          <i class="fas fa-cloud-upload-alt"></i> 上传媒体
        </button>
      </div>
    </div>

    <div class="filter-bar">
      <div class="search-box">
        <input type="text" placeholder="搜索媒体..." v-model="searchQuery" @input="filterMedia">
        <i class="fas fa-search"></i>
      </div>
      <div class="filter-controls">
        <select v-model="typeFilter" @change="filterMedia">
          <option value="">所有类型</option>
          <option value="image">图片</option>
          <option value="document">文档</option>
          <option value="video">视频</option>
          <option value="audio">音频</option>
        </select>
        <select v-model="sortBy" @change="filterMedia">
          <option value="newest">最新上传</option>
          <option value="oldest">最早上传</option>
          <option value="name">名称</option>
          <option value="size">文件大小</option>
        </select>
      </div>
    </div>

    <div class="media-gallery" v-if="filteredMedia.length > 0">
      <div v-for="item in filteredMedia" :key="item.id" class="media-item">
        <div class="media-preview" @click="selectMedia(item)">
          <img v-if="item.type === 'image'" :src="item.url" :alt="item.name">
          <div v-else class="file-icon">
            <i :class="getFileIcon(item.type)"></i>
          </div>
        </div>
        <div class="media-info">
          <div class="media-name">{{ item.name }}</div>
          <div class="media-meta">
            <span>{{ formatSize(item.size) }}</span>
            <span>{{ formatDate(item.uploadDate) }}</span>
          </div>
        </div>
        <div class="media-actions">
          <button class="action-btn" @click="copyUrl(item)">
            <i class="fas fa-link"></i>
          </button>
          <button class="action-btn" @click="deleteMedia(item)">
            <i class="fas fa-trash-alt"></i>
          </button>
        </div>
      </div>
    </div>

    <div class="empty-state" v-else>
      <i class="fas fa-photo-video"></i>
      <p>没有找到媒体文件</p>
      <button class="primary-btn" @click="showUploadModal = true">上传新文件</button>
    </div>

    <!-- 上传模态框 -->
    <div class="modal" v-if="showUploadModal">
      <div class="modal-backdrop" @click="showUploadModal = false"></div>
      <div class="modal-content">
        <div class="modal-header">
          <h3>上传媒体文件</h3>
          <button class="close-btn" @click="showUploadModal = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="upload-area" @dragover.prevent @drop.prevent="onFileDrop" @click="triggerFileInput">
            <input type="file" ref="fileInput" style="display: none" multiple @change="onFileSelect">
            <i class="fas fa-cloud-upload-alt"></i>
            <p>拖放文件到此处或点击上传</p>
            <span>支持JPG, PNG, GIF, PDF, MP4等格式</span>
          </div>
          <div class="upload-list" v-if="uploadQueue.length > 0">
            <div v-for="(file, index) in uploadQueue" :key="index" class="upload-item">
              <div class="upload-item-name">{{ file.name }}</div>
              <div class="upload-progress">
                <div class="progress-bar">
                  <div class="progress" :style="{ width: file.progress + '%' }"></div>
                </div>
                <span>{{ file.progress }}%</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="secondary-btn" @click="showUploadModal = false">取消</button>
          <button class="primary-btn" @click="uploadFiles" :disabled="uploadQueue.length === 0">
            开始上传
          </button>
        </div>
      </div>
    </div>

    <!-- 媒体详情模态框 -->
    <div class="modal" v-if="selectedMedia">
      <div class="modal-backdrop" @click="selectedMedia = null"></div>
      <div class="modal-content media-detail-modal">
        <div class="modal-header">
          <h3>{{ selectedMedia?.name }}</h3>
          <button class="close-btn" @click="selectedMedia = null">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="modal-body">
          <div class="media-detail-preview">
            <img v-if="selectedMedia?.type === 'image'" :src="selectedMedia?.url" :alt="selectedMedia?.name">
            <div v-else class="file-preview">
              <i :class="getFileIcon(selectedMedia?.type)"></i>
            </div>
          </div>
          <div class="media-detail-info">
            <div class="info-group">
              <label>文件名</label>
              <div>{{ selectedMedia?.name }}</div>
            </div>
            <div class="info-group">
              <label>类型</label>
              <div>{{ selectedMedia?.type }}</div>
            </div>
            <div class="info-group">
              <label>大小</label>
              <div>{{ formatSize(selectedMedia?.size) }}</div>
            </div>
            <div class="info-group">
              <label>上传时间</label>
              <div>{{ formatDate(selectedMedia?.uploadDate) }}</div>
            </div>
            <div class="info-group">
              <label>URL</label>
              <div class="url-field">
                <input type="text" readonly :value="selectedMedia?.url">
                <button class="copy-btn" @click="copyUrl(selectedMedia)">
                  <i class="fas fa-copy"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="danger-btn" @click="deleteMedia(selectedMedia)">删除</button>
          <button class="primary-btn" @click="selectedMedia = null">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MediaManager',
  data() {
    return {
      mediaList: [],
      filteredMedia: [],
      searchQuery: '',
      typeFilter: '',
      sortBy: 'newest',
      showUploadModal: false,
      selectedMedia: null,
      uploadQueue: []
    };
  },
  mounted() {
    this.fetchMedia();
  },
  methods: {
    // 获取媒体列表
    async fetchMedia() {
      try {
        // 这里替换为实际API调用
        // const response = await mediaService.getAll();
        // this.mediaList = response.data;
        
        // 临时测试数据
        this.mediaList = [
          {
            id: 1,
            name: 'banner-image.jpg',
            type: 'image',
            url: 'https://images.unsplash.com/photo-1522252234503-e356532cafd5?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=800&q=80',
            size: 1024000,
            uploadDate: new Date('2023-03-10')
          },
          {
            id: 2,
            name: 'documentation.pdf',
            type: 'document',
            url: '/documents/documentation.pdf',
            size: 2048000,
            uploadDate: new Date('2023-02-15')
          },
          {
            id: 3,
            name: 'profile-photo.png',
            type: 'image',
            url: 'https://images.unsplash.com/photo-1555066931-4365d14bab8c?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=800&q=80',
            size: 512000,
            uploadDate: new Date('2023-04-20')
          }
        ];
        
        this.filterMedia();
      } catch (error) {
        console.error('获取媒体列表失败:', error);
        this.$message.error('获取媒体列表失败');
      }
    },
    
    // 过滤和排序媒体
    filterMedia() {
      let result = [...this.mediaList];
      
      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        result = result.filter(item => 
          item.name.toLowerCase().includes(query)
        );
      }
      
      // 类型过滤
      if (this.typeFilter) {
        result = result.filter(item => item.type === this.typeFilter);
      }
      
      // 排序
      result.sort((a, b) => {
        switch (this.sortBy) {
          case 'newest':
            return new Date(b.uploadDate) - new Date(a.uploadDate);
          case 'oldest':
            return new Date(a.uploadDate) - new Date(b.uploadDate);
          case 'name':
            return a.name.localeCompare(b.name);
          case 'size':
            return b.size - a.size;
          default:
            return 0;
        }
      });
      
      this.filteredMedia = result;
    },
    
    // 选择媒体项
    selectMedia(item) {
      this.selectedMedia = item;
    },
    
    // 复制URL
    copyUrl(item) {
      navigator.clipboard.writeText(item.url)
        .then(() => {
          alert('URL已复制到剪贴板');
        })
        .catch(err => {
          console.error('复制失败:', err);
        });
    },
    
    // 删除媒体
    deleteMedia(item) {
      if (confirm(`确定要删除 ${item.name} 吗？`)) {
        // 这里替换为实际API调用
        // await mediaService.delete(item.id);
        this.mediaList = this.mediaList.filter(media => media.id !== item.id);
        this.filterMedia();
        
        if (this.selectedMedia && this.selectedMedia.id === item.id) {
          this.selectedMedia = null;
        }
      }
    },
    
    // 触发文件选择器
    triggerFileInput() {
      this.$refs.fileInput.click();
    },
    
    // 选择文件处理
    onFileSelect(event) {
      const files = event.target.files;
      this.addFilesToQueue(files);
    },
    
    // 拖放文件处理
    onFileDrop(event) {
      const files = event.dataTransfer.files;
      this.addFilesToQueue(files);
    },
    
    // 添加文件到上传队列
    addFilesToQueue(files) {
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        this.uploadQueue.push({
          file: file,
          name: file.name,
          progress: 0,
          status: 'pending'
        });
      }
    },
    
    // 上传文件
    async uploadFiles() {
      for (let i = 0; i < this.uploadQueue.length; i++) {
        const item = this.uploadQueue[i];
        item.status = 'uploading';
        
        // 模拟上传进度
        const updateProgress = setInterval(() => {
          if (item.progress < 100) {
            item.progress += 10;
            this.$set(this.uploadQueue, i, item);
          } else {
            clearInterval(updateProgress);
          }
        }, 300);
        
        // 这里替换为实际API调用
        // const formData = new FormData();
        // formData.append('file', item.file);
        // await mediaService.upload(formData);
        
        // 模拟上传完成
        await new Promise(resolve => setTimeout(resolve, 3000));
        
        item.progress = 100;
        item.status = 'completed';
        this.$set(this.uploadQueue, i, item);
      }
      
      // 刷新媒体列表
      await this.fetchMedia();
      
      // 清空上传队列
      setTimeout(() => {
        this.uploadQueue = [];
        this.showUploadModal = false;
      }, 1000);
    },
    
    // 获取文件图标
    getFileIcon(type) {
      switch (type) {
        case 'image':
          return 'fas fa-file-image';
        case 'document':
          return 'fas fa-file-pdf';
        case 'video':
          return 'fas fa-file-video';
        case 'audio':
          return 'fas fa-file-audio';
        default:
          return 'fas fa-file';
      }
    },
    
    // 格式化文件大小
    formatSize(bytes) {
      if (!bytes) return '0 Bytes';
      
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      
      const d = new Date(date);
      return d.toLocaleDateString('zh-CN');
    }
  }
};
</script>

<style scoped>
.media-manager {
  padding: 20px 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  font-weight: 700;
  color: var(--dark-text);
  margin: 0;
}

.primary-btn {
  background: linear-gradient(135deg, #4361ee, #3a0ca3);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(67, 97, 238, 0.2);
}

.primary-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(67, 97, 238, 0.3);
}

.secondary-btn {
  background: #f5f7fb;
  color: var(--dark-text);
  border: 1px solid #e0e0e0;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.secondary-btn:hover {
  background: #e9ecef;
}

.danger-btn {
  background: var(--danger-color);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.danger-btn:hover {
  background: #c92a2a;
}

.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box input {
  width: 100%;
  padding: 10px 15px 10px 40px;
  border-radius: 30px;
  border: 1px solid #e0e0e0;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-box input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
}

.search-box i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #aaa;
}

.filter-controls {
  display: flex;
  gap: 15px;
}

.filter-controls select {
  padding: 8px 15px;
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  background-color: white;
  font-size: 14px;
  cursor: pointer;
}

.filter-controls select:focus {
  outline: none;
  border-color: var(--primary-color);
}

.media-gallery {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.media-item {
  background-color: white;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.media-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.media-preview {
  height: 150px;
  background-color: #f8f9fa;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.media-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.media-preview:hover img {
  transform: scale(1.05);
}

.file-icon {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.media-info {
  padding: 12px;
  flex-grow: 1;
}

.media-name {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 5px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.media-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
}

.media-actions {
  display: flex;
  justify-content: space-between;
  padding: 0 12px 12px;
}

.action-btn {
  width: 30px;
  height: 30px;
  border-radius: 6px;
  background: #f5f7fb;
  border: 1px solid #e0e0e0;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  background: white;
  border-radius: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.empty-state i {
  font-size: 50px;
  color: #ccc;
  margin-bottom: 20px;
}

.empty-state p {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
}

/* 模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(3px);
}

.modal-content {
  position: relative;
  width: 95%;
  max-width: 600px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  animation: modal-fade-in 0.3s ease;
  max-height: 80vh;
}

@keyframes modal-fade-in {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--dark-text);
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  color: #666;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background-color: #f5f7fb;
  color: var(--danger-color);
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 15px 20px;
  border-top: 1px solid #f0f0f0;
}

/* 上传区域样式 */
.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.upload-area:hover {
  border-color: var(--primary-color);
  background-color: rgba(67, 97, 238, 0.05);
}

.upload-area i {
  font-size: 40px;
  color: var(--primary-color);
  margin-bottom: 15px;
}

.upload-area p {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 10px;
}

.upload-area span {
  font-size: 14px;
  color: #666;
}

.upload-list {
  margin-top: 20px;
}

.upload-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  margin-bottom: 10px;
}

.upload-item-name {
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.upload-progress {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar {
  width: 100px;
  height: 6px;
  background-color: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background-color: var(--primary-color);
  border-radius: 3px;
  transition: width 0.3s ease;
}

/* 媒体详情模态框样式 */
.media-detail-modal {
  max-width: 800px;
}

.media-detail-preview {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
  max-height: 300px;
  overflow: hidden;
}

.media-detail-preview img {
  max-width: 100%;
  max-height: 250px;
  object-fit: contain;
}

.file-preview {
  width: 100px;
  height: 100px;
  background-color: var(--primary-color);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 36px;
}

.media-detail-info {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.info-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-group label {
  font-size: 12px;
  color: #666;
}

.info-group div {
  font-size: 14px;
  color: var(--dark-text);
  font-weight: 500;
}

.url-field {
  display: flex;
  align-items: center;
  gap: 10px;
}

.url-field input {
  flex-grow: 1;
  padding: 8px 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  background-color: #f8f9fa;
}

.copy-btn {
  background: none;
  border: none;
  color: var(--primary-color);
  cursor: pointer;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-box {
    width: 100%;
  }
  
  .filter-controls {
    flex-direction: column;
  }
  
  .media-gallery {
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  }
  
  .media-detail-info {
    grid-template-columns: 1fr;
  }
}
</style> 